let exec = require("../DBhelper").exec
class Cart {
    async add(req, res) {
        let { uid, gid, gname, gprice, gnumber, gurl } = req.body

        let sql = "select * from carts where cstatus=1 and gid=? and uid=? ;"
        let params = [gid, uid]
        let result = await exec(sql, params)
        let isAdd = result && result.length >= 1
        if (isAdd) {
            let sql_update = "update carts set cnumber=cnumber+?,cmoney=cnumber*cprice where gid=? and uid=? ;"
            let update_result = await exec(sql_update, [gnumber, gid, uid])
            let isUpdate = update_result.affectedRows >= 1
            res.json({
                msg: isUpdate ? "加入购物车成功u" : "加入购物车失败u"
            })
        } else {
            let sql_insert = "insert into carts (uid,gid,cname,curl,cprice,cnumber,cmoney) value(?,?,?,?,?,?,?);"
            let params = [uid, gid, gname, gurl, gprice, gnumber, gnumber * gprice]
            let insert_result = await exec(sql_insert, params)
            let isInsert = insert_result && insert_result.affectedRows >= 1
            res.json({
                msg: isInsert ? "加入购物车成功i" : "加入购物车失败i"
            })
        }
    }
    async getcarts(req, res) {
        let sql = "select * from carts where cstatus=1 and uid=? ;";
        let result = await exec(sql, [req.params.uid]);
        res.json({ msg: '查询成功', data: result, code: 1 })
    }


    async modifiy(req, res) {
        let sql = "update carts set cnumber=? ,cmoney=cnumber*cprice where cid=? and cstatus=1";
        let params = [req.body.cnumber, req.body.cid];
        let result = await exec(sql, params);
        let isModifiy = result.affectedRows >= 1;
        res.json({ msg: isModifiy ? '修改成功' : '修改失败', code: isModifiy ? 1 : -1 })
    }

    async delete(req, res) {
        let sql = "update carts set cstatus=0 where cid=? and cstatus=1";
        let params = [req.body.cid];
        let result = await exec(sql, params);
        let isModifiy = result.affectedRows >= 1;
        res.json({ msg: isModifiy ? '删除成功' : '删除失败', code: isModifiy ? 1 : -1 })

    }
}

module.exports = new Cart();